//
//  CommunityViewController.m
//  A Cup
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 doll. All rights reserved.
//

#import "CommunityViewController.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "CommunityData.h"
#import "MJRefresh.h"
#import "CommunityTextCell.h"
#import "CommunityIMGTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "todayTopicViewController.h"
#import "AboutUsViewController.h"
#import "SaveCupViewController.h"
#import "dataBaseHandle.h"
#define HEIGHT self.view.frame.size.height
#define WIDTH self.view.frame.size.width
@interface CommunityViewController ()
@property(nonatomic,assign)NSInteger pageNew;
@property(nonatomic,assign)NSInteger pageHot;
@property(nonatomic,retain)NSMutableArray *listNewArr;
@property(nonatomic,retain)NSMutableArray *listHotArr;
@property(nonatomic,retain)NSMutableArray *imgArr;
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,assign)NSInteger tag;
@property(nonatomic,retain)UISegmentedControl *seg;
@property(nonatomic,retain)NSNumber *total;
@property(nonatomic, retain)UIView *logoview;
@property(nonatomic ,retain)UITableView *tabel;
@property(nonatomic, retain)NSMutableArray *arr;
@property(nonatomic, assign)BOOL isclick;
@property(nonatomic, retain)UIButton *button;
@property(nonatomic, retain)UIActivityIndicatorView *activity;
@end

@implementation CommunityViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"社区";
        self.listNewArr = [NSMutableArray array];
        self.listHotArr = [NSMutableArray array];
        self.imgArr = [NSMutableArray array];
        self.imgArr = [NSMutableArray array];
        UIImage *musicImage0 = [UIImage imageNamed:@"todayMusic0"];
        [self.imgArr addObject:musicImage0];
        UIImage *musicImage1 = [UIImage imageNamed:@"todayMusic1"];
        [self.imgArr addObject:musicImage1];
        UIImage *musicImage2 = [UIImage imageNamed:@"todayMusic2"];
        [self.imgArr addObject:musicImage2];
        UIImage *musicImage3 = [UIImage imageNamed:@"todayMusic3"];
        [self.imgArr addObject:musicImage3];
        UIImage *musicImage4 = [UIImage imageNamed:@"todayMusic4"];
        [self.imgArr addObject:musicImage4];
        UIImage *musicImage5 = [UIImage imageNamed:@"todayMusic5"];
        [self.imgArr addObject:musicImage5];
        UIImage *musicImage6 = [UIImage imageNamed:@"todayMusic6"];
        [self.imgArr addObject:musicImage6];
        UIImage *musicImage7 = [UIImage imageNamed:@"todayMusic7"];
        [self.imgArr addObject:musicImage7];
        UIImage *musicImage8 = [UIImage imageNamed:@"todayMusic8"];
        [self.imgArr addObject:musicImage8];
        UIImage *musicImage9 = [UIImage imageNamed:@"todayMusic9"];
        [self.imgArr addObject:musicImage9];
        UIImage *musicImage10 = [UIImage imageNamed:@"todayMusic10"];
        [self.imgArr addObject:musicImage10];
        UIImage *musicImage11 = [UIImage imageNamed:@"todayMusic11"];
        [self.imgArr addObject:musicImage11];
        UIImage *musicImage12 = [UIImage imageNamed:@"todayMusic12"];
        [self.imgArr addObject:musicImage12];
        self.isclick = YES;
        self.tag = 0;
        self.pageHot = 0;
        self.pageNew = 0;
    }
    return self;
}

- (void)dataNew
{
    if ([dataBaseHandle shareDB].state == 1) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSString *start = [NSString stringWithFormat:@"%ld",self.pageNew*10];
        NSDictionary *dic = @{@"deviceid":@"D8FDE94C-841F-4A4D-B5C4-AAD2472CEE85",@"client":@"1",@"sort":@"addtime",@"limit":@"10",@"version":@"3.0.1",@"start":start,@"auth":@""};
        [manager POST:@"http://api2.pianke.me/group/posts_hotlist" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *data = [responseObject objectForKey:@"data"];
            self.total = [data objectForKey:@"total"];
            NSArray *list = [data objectForKey:@"list"];
            for (NSDictionary *tempDic in list) {
                CommunityData *community = [[CommunityData alloc]init];
                [community setValuesForKeysWithDictionary:tempDic];
                [self.listNewArr addObject:community];
                [community release];
            }
            [self.tableView reloadData];
            [self.tableView.legendHeader endRefreshing];
            [self.tableView.legendFooter endRefreshing];
            self.pageNew ++;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前无网络，请检查网络后重新尝试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}
- (void)dataHot
{
    if ([dataBaseHandle shareDB].state == 1) {
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSString *start = [NSString stringWithFormat:@"%ld",self.pageHot*10];
        NSDictionary *dic = @{@"deviceid":@"D8FDE94C-841F-4A4D-B5C4-AAD2472CEE85",@"client":@"1",@"sort":@"hot",@"limit":@"10",@"version":@"3.0.1",@"start":start,@"auth":@""};
        [manager POST:@"http://api2.pianke.me/group/posts_hotlist" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *data = [responseObject objectForKey:@"data"];
            NSArray *list = [data objectForKey:@"list"];
            for (NSDictionary *tempDic in list) {
                CommunityData *community = [[CommunityData alloc]init];
                [community setValuesForKeysWithDictionary:tempDic];
                [self.listHotArr addObject:community];
                [community release];
            }
            [self.tableView reloadData];
            [self.tableView.legendFooter endRefreshing];
            [self.tableView.legendHeader endRefreshing];
            self.pageHot ++;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前无网络，请检查网络后重新尝试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}
- (void)methodNew
{
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.listNewArr removeAllObjects];
            [self.tableView reloadData];
            self.pageNew = 0;
            [self dataNew];
        });
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [self dataNew];
    }];
}
- (void)methodHot
{
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.listHotArr removeAllObjects];
            self.pageHot = 0;
            [self dataHot];
        });
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [self dataHot];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
            self.tabBarController.tabBar.hidden = NO;

    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = NO;
    self.seg = [[UISegmentedControl alloc]initWithItems:@[@"最新",@"最热"]];
    self.seg.frame = CGRectMake(0, 0, self.view.frame.size.width,30);
    self.seg.selectedSegmentIndex = 0;
    self.seg.tintColor = [UIColor grayColor];
    [self.view addSubview:self.seg];
    [_seg release];
    [self.seg addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventValueChanged];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height - 30) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self.view bringSubviewToFront:self.tableView];
    [_tableView release];
    
    self.activity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, 100, 30, 30)];
    [self.activity setCenter:CGPointMake(self.view.frame.size.width / 2, (self.view.frame.size.height - 113) / 2)]; // 指定进度轮中心点
    [self.activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:self.activity];
    [self.view bringSubviewToFront:self.activity];
    [self.activity startAnimating];
    [_activity release];
    
    if (self.tag == 0) {
        [self.tableView.legendFooter beginRefreshing];
        [self dataNew];
        [self methodNew];
    }else{
        [self.tableView.legendFooter beginRefreshing];
        [self dataHot];
        [self methodHot];
    }

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Top" forState:UIControlStateNormal];
    button.frame = CGRectMake(0.8 * WIDTH, 0.7 * HEIGHT - 10, 36, 36);
    button.layer.borderWidth = 1;
    button.backgroundColor = [UIColor blackColor];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.clipsToBounds = YES;
    button.alpha = 0.8;
    button.layer.cornerRadius = 18;
    [button addTarget:self action:@selector(moveToTop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    // Do any additional setup after loading the view.
}

- (void)moveToTop
{
    self.tableView.contentOffset = CGPointMake(0, 0);
}

- (void)segClick:(UISegmentedControl *)seg
{
    switch (self.seg.selectedSegmentIndex) {
        case 0:
            self.tag = 0;
            [self.tableView reloadData];
            [self methodNew];
            break;
        case 1:
            self.tag = 1;
            [self.tableView reloadData];
            [self dataHot];
            [self.tableView reloadData];
            [self methodHot];
            break;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.tag == 0) {
        if (self.listNewArr.count>0) {
            [self.activity stopAnimating];
        }
        return self.listNewArr.count;
    }else{
        if (self.listHotArr.count > 0) {
            [self.activity stopAnimating];
        }
        return self.listHotArr.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommunityData *community = [[CommunityData alloc]init];
    if (self.tag == 0) {
        community = self.listNewArr[indexPath.row];
    }else{
        community = self.listHotArr[indexPath.row];
    }
    if ([community.coverimg isEqualToString:@""]&&[community.songid isEqualToString:@""]) {
        static NSString *reuse = @"cell1";
        CommunityTextCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (cell == nil) {
            cell = [[CommunityTextCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        }
        cell.title.text = community.title;
        cell.content.text = community.content;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        static NSString *reuse = @"cell2";
        CommunityIMGTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (cell == nil) {
            cell = [[CommunityIMGTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        }
        cell.title.text = community.title;
        cell.content.text = community.content;
        if (![community.songid isEqualToString:@""]) {
            UIImage *image = self.imgArr[arc4random()%13];
            cell.coverIMG.image = image;
        }else{
            NSURL *imgURL = [NSURL URLWithString:community.coverimg];
            [cell.coverIMG sd_setImageWithURL:imgURL];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        
        if (self.tag == 0) {
            CommunityData *community = self.listNewArr[indexPath.row];
            todayTopicViewController *today = [[todayTopicViewController alloc] init];
            today.coverimgString = community.coverimg;
            today.idNum = community.contentid;
            [self.navigationController pushViewController:today animated:YES];
            [today release];
        }else{
            CommunityData *community = self.listHotArr[indexPath.row];
            todayTopicViewController *today = [[todayTopicViewController alloc] init];
            today.idNum = community.contentid;
            today.coverimgString = community.coverimg;
            [self.navigationController pushViewController:today animated:YES];
            [today release];
      }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
